package com.lfs.admin.config;

import com.lfs.admin.model.dto.ShopDto;
import com.lfs.admin.model.entity.ShopEntity;
import com.lfs.admin.service.ShopService;
import com.lfs.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private ShopService shopService;

    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer() {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        return container;
    }

    @Bean
    KeyExpirationEventMessageListener keyExpirationListener() {
        return new KeyExpirationEventMessageListener(redisMessageListenerContainer()) {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                log.info("过期redis数据：{}", message.toString());
                try {
                    String key = message.toString();
                    //从失效key中筛选代表session失效的key
                    String sessionKey = "shopId:";
                    if (null != key && key.startsWith(sessionKey)) {
                        log.info("shopId:{}已到达消息存储最大时间,自动清理会话记录", key);
                        String shopId = key.substring(key.indexOf(":") + 1);
                        String status = CommonConstants.SHOP_GRANT_EXPIRE;
                        ShopEntity shopEntity = ShopEntity.builder()
                                .status(status)
                                .shopId(shopId).build();
                        shopService.updateShopInfo(shopEntity);
                    }
                } catch (Exception e) {
                    log.error("【修改历史会话消息状态异常】：{}", e.getMessage());
                }
            }
        };
    }
}
